﻿// (c) Copyright Clovis Coli Jr.
// This source is subject to the Microsoft Public License.
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
// All other rights reserved.

using System;
using System.Windows;
using System.Text.RegularExpressions;

namespace BrasilFramework.Controle.WPF.Comum.Validacao
{
    public class RegexValidator : ValidatorBase
	{
	    public Regex RegExpression
		{
			get { return (Regex)GetValue(RegExpressionProperty); }
			set { SetValue(RegExpressionProperty, value); }
		}

        public static readonly DependencyProperty RegExpressionProperty =
			DependencyProperty.Register("RegExpression", typeof(Regex), typeof(RegexValidator), new PropertyMetadata(null));
			
		public string Expression
		{
			get { return (string)GetValue(ExpressionProperty); }
			set { SetValue(ExpressionProperty, value); }
		}

        public static readonly DependencyProperty ExpressionProperty =
			DependencyProperty.Register("Expression", typeof(string), typeof(RegexValidator), new PropertyMetadata(ExpressionPropertyChangedCallback));

		public static void ExpressionPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			try
			{
				d.SetValue(RegExpressionProperty, 
					new Regex(e.NewValue.ToString()));
			}
			catch{
				d.SetValue(RegExpressionProperty, null);
			}
		}
		

		protected override bool ValidateControl()
		{
			if (ElementToValidate is System.Windows.Controls.TextBox && RegExpression!=null)
			{
				var box = ElementToValidate as System.Windows.Controls.TextBox;
				return String.IsNullOrEmpty(box.Text) || RegExpression.Match(box.Text).Success;
			}
			return true;
		}
	}
}
